package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.datasync.SyncDatabase;
import com.ruoyi.system.service.ISyncDatabaseService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 数据库管理Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/sync/database")
public class SyncDatabaseController extends BaseController
{
    @Autowired
    private ISyncDatabaseService syncDatabaseService;

    /**
     * 查询数据库列表
     */
    @PreAuthorize("@ss.hasPermi('system:database:list')")
    @GetMapping("/list")
    public TableDataInfo list(SyncDatabase syncDatabase)
    {
        startPage();
        List<SyncDatabase> list = syncDatabaseService.selectSyncDatabaseList(syncDatabase);
        return getDataTable(list);
    }

    /**
     * 导出数据库列表
     */
    @PreAuthorize("@ss.hasPermi('system:database:export')")
    @Log(title = "数据库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SyncDatabase syncDatabase)
    {
        List<SyncDatabase> list = syncDatabaseService.selectSyncDatabaseList(syncDatabase);
        ExcelUtil<SyncDatabase> util = new ExcelUtil<SyncDatabase>(SyncDatabase.class);
        util.exportExcel(response, list, "数据库数据");
    }

    /**
     * 获取数据库详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:database:query')")
    @GetMapping(value = "/{dbId}")
    public AjaxResult getInfo(@PathVariable("dbId") Long dbId)
    {
        return AjaxResult.success(syncDatabaseService.selectSyncDatabaseByDbId(dbId));
    }

    /**
     * 新增数据库
     */
    @PreAuthorize("@ss.hasPermi('system:database:add')")
    @Log(title = "数据库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SyncDatabase syncDatabase)
    {
        return toAjax(syncDatabaseService.insertSyncDatabase(syncDatabase));
    }

    /**
     * 修改数据库
     */
    @PreAuthorize("@ss.hasPermi('system:database:edit')")
    @Log(title = "数据库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SyncDatabase syncDatabase)
    {
        return toAjax(syncDatabaseService.updateSyncDatabase(syncDatabase));
    }

    /**
     * 删除数据库
     */
    @PreAuthorize("@ss.hasPermi('system:database:remove')")
    @Log(title = "数据库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dbIds}")
    public AjaxResult remove(@PathVariable Long[] dbIds)
    {
        return toAjax(syncDatabaseService.deleteSyncDatabaseByDbIds(dbIds));
    }
    
    /**
     * 测试数据库连接
     */
    @PreAuthorize("@ss.hasPermi('system:database:test')")
    @GetMapping("/test/{dbId}")
    public AjaxResult testConnection(@PathVariable("dbId") Long dbId)
    {
        boolean result = syncDatabaseService.testDatabaseConnection(dbId);
        return result ? AjaxResult.success("连接成功") : AjaxResult.error("连接失败");
    }
    
    /**
     * 获取数据库下拉选项列表
     */
    @GetMapping("/options")
    public AjaxResult getDatabaseOptions()
    {
        List<SyncDatabase> options = syncDatabaseService.selectDatabaseOptions();
        return AjaxResult.success(options);
    }
    
    /**
     * 本地备份数据库
     */
    @PreAuthorize("@ss.hasPermi('system:database:backup')")
    @Log(title = "数据库本地备份", businessType = BusinessType.EXPORT)
    @GetMapping("/backup/{dbId}")
    public AjaxResult backupDatabase(@PathVariable("dbId") Long dbId)
    {
        String backupFilePath = syncDatabaseService.backupDatabase(dbId);
        if (backupFilePath != null) {
            // 获取数据库名称
            SyncDatabase database = syncDatabaseService.selectSyncDatabaseByDbId(dbId);
            String dbName = (database != null) ? database.getDbName() : "unknown";
            
            // 返回成功信息和文件路径
            return AjaxResult.success("备份成功，文件路径：" + backupFilePath);
        } else {
            return AjaxResult.error("备份失败，请检查数据库连接和服务器配置");
        }
    }
    
    /**
     * 远程备份数据库
     */
    @PreAuthorize("@ss.hasPermi('system:database:backup')")
    @Log(title = "数据库远程备份", businessType = BusinessType.EXPORT)
    @PostMapping("/remote-backup/{dbId}")
    public AjaxResult remoteBackupDatabase(@PathVariable("dbId") Long dbId, @RequestBody Map<String, Object> params)
    {
        Long targetServerId = Long.valueOf(params.get("targetServerId").toString());
        String backupPath = params.get("backupPath") != null ? params.get("backupPath").toString() : null;
        
        if (targetServerId == null) {
            return AjaxResult.error("目标服务器ID不能为空");
        }
        
        String backupFilePath = syncDatabaseService.remoteBackupDatabase(dbId, targetServerId, backupPath);
        if (backupFilePath != null) {
            return AjaxResult.success("远程备份成功，文件路径：" + backupFilePath);
        } else {
            return AjaxResult.error("远程备份失败");
        }
    }
    
    /**
     * 获取数据库表结构
     */
    @PreAuthorize("@ss.hasPermi('system:database:query')")
    @GetMapping("/tables/{dbId}")
    public AjaxResult getDatabaseTables(@PathVariable("dbId") Long dbId)
    {
        List<Map<String, Object>> tables = syncDatabaseService.getDatabaseTables(dbId);
        return AjaxResult.success(tables);
    }
    
    /**
     * 获取表字段结构
     */
    @PreAuthorize("@ss.hasPermi('system:database:query')")
    @GetMapping("/columns/{dbId}/{tableName}")
    public AjaxResult getTableColumns(@PathVariable("dbId") Long dbId, @PathVariable("tableName") String tableName)
    {
        List<Map<String, Object>> columns = syncDatabaseService.getTableColumns(dbId, tableName);
        return AjaxResult.success(columns);
    }
    
    /**
     * 执行SQL查询
     */
    @PreAuthorize("@ss.hasPermi('system:database:query')")
    @PostMapping("/execute/{dbId}")
    public AjaxResult executeQuery(@PathVariable("dbId") Long dbId, @RequestBody Map<String, String> params)
    {
        String sql = params.get("sql");
        if (sql == null || sql.trim().isEmpty()) {
            return AjaxResult.error("SQL语句不能为空");
        }
        
        Map<String, Object> result = syncDatabaseService.executeQuery(dbId, sql);
        if ((Boolean) result.get("success")) {
            return AjaxResult.success(result);
        } else {
            return AjaxResult.error((String) result.get("message"));
        }
    }

    /**
     * 更新数据库备份设置
     */
    @PreAuthorize("@ss.hasPermi('system:database:edit')")
    @Log(title = "数据库备份设置", businessType = BusinessType.UPDATE)
    @PutMapping("/backup-settings")
    public AjaxResult updateBackupSettings(@RequestBody SyncDatabase syncDatabase)
    {
        if (syncDatabase.getDbId() == null) {
            return AjaxResult.error("数据库ID不能为空");
        }
        
        return toAjax(syncDatabaseService.updateDatabaseBackupSettings(syncDatabase));
    }
} 